import React, { useEffect, useState } from 'react';
import { Table, Form, Select, Button, Typography, Flex, InputNumber, Input, DatePicker, Tooltip, Modal } from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { transformArray, download } from '../../../utils/commonUtil';
import { apiBigSimulationFileSummaryFilter, apiBigSimulationFileSummaryList, apiBigSimulationFileSummaryDownload, apiBigSimulationFileSummaryDynamicField, apiBigSimulationFileSummaryMeterHeader } from '../../../services/bigSimulationFile/summary';
import { CONFIG_ITEM_KEYS, DATEFORMAT, APPROVAL_STATUS } from '../../../utils/constant';
import './index.scss';
import dayjs from 'dayjs';
import FileAnalysisContent from '../Components/FileAnalysisContent';
import { filter } from 'lodash';

const { Title } = Typography;
const { Option } = Select;
const BigSimulationFileSummaryData = () => {
  const { APPROVED } = APPROVAL_STATUS;
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [formDynamic] = Form.useForm();
  const { BU, MODULE } = CONFIG_ITEM_KEYS;
  // 分页相关
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalPage, setTotalPage] = useState();
  // list 页面数据
  const [dataList, setDataList] = useState();
  // 下拉框数据
  const [buList, setBuList] = useState([]);
  const [projectList, setProjectList] = useState([]);
  const [productList, setProductList] = useState([]);
  const [requesterList, setRequesterList] = useState([]);
  const [statusList, setStatus] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [filedItems, setFiledItems] = useState([]);
  const [filedItemsValues, setFiledItemsValues] = useState([]);
  const [itemOption, setItemOption] = useState([]);
  const [formInitValues, setFormInitValues] = useState({
    dynamicFields: [],
  });
  const [tableColumns, setTableColumns] = useState([]);
  const [contentView, setContentView] = useState(false);
  const [recordData, setRecordData] = useState([]);
  const fieldTypeList = [
    {
      value: 'Date picker',
      label: 'Date picker',
    },
    {
      value: 'Number Input',
      label: 'Number Input',
    },
    {
      value: 'Text Input',
      label: 'Text Input',
    },
    {
      value: 'Dropdown',
      label: 'Dropdown',
    },
  ];

  const getQueryParams = () => {
    const formData = form.getFieldsValue();
    const params = {
      buTypes: formData?.buTypes || [],
      moduleNames: formData?.moduleNames || [],
      projectNames: formData?.projectNames || [],
      requesters: formData?.requesters || [],
      requestStatus: formData?.requestStatus || [],
      keywords: formData?.keywords || '',
      dynamicFields: formData?.dynamicFields?.map((item) => {
        const itemData = { ...item };
        itemData.fieldValue = item?.fieldType === 'Date picker' ? item?.fieldValue && dayjs(item?.fieldValue)?.format(DATEFORMAT) : item?.fieldType === 'Dropdown' ? item?.fieldValue && item?.fieldValue?.join(',') : item?.fieldValue;
        return itemData
      }) || [],
    };
    return params;
  };
  const serach = () => {
    setCurrentPage(1);
    queryList(1);
  };

  const fileAnalysisContentView = (record) => {
    setRecordData(record);
    setContentView(true);
  };

  // 获取动态表头
  const apiBigSimulationFileSummaryMeterHeaderAsync = () => {
    const transList = ['buType', 'moduleName', 'templateName', 'projectName', 'productName', 'requestStatus', 'requester', 'fileAnalysisContent'];
    apiBigSimulationFileSummaryMeterHeader().then((res) => {
      if (res?.data?.code === 200) {
        const renderColumns = res?.data?.data?.meterHeaderNames?.filter(val => val !== 'fileAnalysisContent')?.map(item => {
          return {
            title: transList.includes(item) ? t(`common.${item}`) : item,
            dataIndex: item === 'requester' ? 'createdBy' : item,
            width: 150,
            align: 'center',
            ellipsis: {
              showTitle: false,
            },
            render: (text, record) => (
              <Tooltip placement="topLeft" title={text}>
                {text}
              </Tooltip>
            ),
          }
        });
        renderColumns.push({
          title: t(`common.fileAnalysisContent`),
          dataIndex: 'fileAnalysisContent',
          width: 150,
          align: 'center',
          fixed: 'right',
          render: (text, record) => (
            <>
              <Button type='link' onClick={() => { fileAnalysisContentView(record) }}>{t('common.details')}</Button>
            </>
          )
        });
        setTableColumns(renderColumns);
      };
    });
  };
  // 获取页面list数据
  const queryList = async (pagination, size) => {
    const params = {
      ...getQueryParams(),
      page: pagination || currentPage,
      limit: size || pageSize
    };
    apiBigSimulationFileSummaryList(params).then((res) => {
      setDataList(res?.data?.data?.items);
      setTotalPage(res?.data?.data?.total);
    });
  };

  // 调用下拉框api
  const apiSelectAsync = async () => {
    apiBigSimulationFileSummaryFilter().then((res) => {
      if (res?.data?.code === 200) {
        setBuList(transformArray(res?.data?.data?.buType));
        setProjectList(transformArray(res?.data?.data?.projectName));
        setProductList(transformArray(res?.data?.data?.productName));
        setStatus(transformArray(res?.data?.data?.requestStatus));
        setRequesterList(transformArray(res?.data?.data?.requester));
      }
    });
  };

  const downloadHandle = async () => {
    apiBigSimulationFileSummaryDownload({ productIds: selectedRowKeys }).then((res) => {
      if (res?.data) {
        download(res)
      }
    })
  };
  const onSelectChange = (newSelectedRowKeys) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const fieldTypeChange = (val) => {
    apiBigSimulationFileSummaryDynamicField({ fieldType: val }).then((res) => {
      if (res?.data?.code === 200) {
        formDynamic?.setFieldValue('filedItem', '');
        setFiledItems(transformArray(res?.data?.data?.fieldNames));
        setFiledItemsValues(res?.data?.data?.fieldValues);
      };
    })
  };
  const filedItemChange = (val) => {
    let itemValues = '';
    for (let item of filedItemsValues) {
      if (item?.[val]) {
        itemValues = item?.[val];
        break;
      };
    };
    const itemOption = itemValues?.split(',');
    setItemOption(itemOption);
  };

  const filedItemAdd = () => {
    formDynamic.validateFields().then(() => {
      let dynamicFieldsData = [...form?.getFieldsValue()?.dynamicFields || []];
      console.log(dynamicFieldsData);
      dynamicFieldsData?.push(
        {
          fieldType: formDynamic?.getFieldsValue()?.fieldType,
          fieldScope: formDynamic?.getFieldsValue()?.fieldType === 'Number Input' ? 'greaterThanOrEqual' : '',
          fieldValue: formDynamic?.getFieldsValue()?.fieldType === 'Dropdown' ? [] : '',
          fieldName: formDynamic?.getFieldsValue()?.filedItem,
          fieldValues: formDynamic?.getFieldsValue()?.fieldType === 'Dropdown' ? itemOption : [],
        }
      );
      console.log(dynamicFieldsData);
      form.setFieldValue('dynamicFields', dynamicFieldsData);
      formDynamic.resetFields();
    }, () => {
      return false;
    });

  };
  const onChangeDatePicker = (date, dateString) => {
    console.log(form.getFieldsValue());
    console.log(date, dateString);
  };
  const selectBefore = (index) => {
    return (
      <Select defaultValue="greaterThanOrEqual" onChange={(val) => {
        const dynamicFieldsData = form?.getFieldsValue()?.dynamicFields;
        dynamicFieldsData[index].fieldScope = val;
        form.setFieldValue('dynamicFields', dynamicFieldsData);
        console.log(form?.getFieldsValue());
      }}>
        <Option value="greaterThanOrEqual">{`>=`}</Option>
        <Option value="lessThanOrEqual">{`<=`}</Option>
        <Option value="greaterThan">{`>`}</Option>
        <Option value="lessThan">{`<`}</Option>
        <Option value="equalTo">{`=`}</Option>
      </Select>
    );
  }
  useEffect(() => {
    // 正式数据
    queryList();
    // 调用下拉框api
    apiSelectAsync();
    // 动态表头
    apiBigSimulationFileSummaryMeterHeaderAsync();
  }, [])

  return (
    <>
      <div className='page-title-wrap'>
        <Flex align='center' justify='space-between'>
          <Title className='fontStyleH2' level={2} >{t('bigSimulationFile.summaryData')}</Title>
          <Button onClick={() => { downloadHandle() }}>{t('common.download')}</Button>
        </Flex>
      </div>
      <div className='page-content-wrap big-file-wrap'>
        <Form form={form} className='filter-wrap' initialValues={formInitValues} name='bigFileFilterform' onValuesChange={(val, allValues) => {

        }}>
          <Flex align='center' className='big-file-summary-filter-wrap'>
            <Form.Item name="buTypes"
              label={t('common.bu')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={buList} />
            </Form.Item>
            <Form.Item name="projectNames"
              label={t('common.project')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={projectList} />
            </Form.Item>
            <Form.Item name="productNames"
              label={t('common.product')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={productList} />
            </Form.Item>

            <Form.Item name="requesters"
              label={t('common.requester')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={requesterList} />
            </Form.Item>
            <Form.Item name="requestStatus"
              initialValue={[APPROVED]}
              label={t('common.status')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Select mode="multiple" placeholder={t('common.pleaseSelect')} allowClear options={statusList} />
            </Form.Item>
            <Form.Item name="keywords"
              label={t('common.keywords')} style={{ width: 160 }} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
              <Input placeholder={t('common.PleaseInput')} />
            </Form.Item>

            <Form.List name="dynamicFields">
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => {
                    const fieldItem = form?.getFieldsValue()?.dynamicFields?.[index];
                    const fieldName = fieldItem?.fieldName;
                    const fieldOption = transformArray(fieldItem?.fieldValues);
                    return (
                      <Flex key={field.key} align='center'>
                        <Form.Item
                          className='dynamic-item'
                          label={fieldName}
                          name={[field.name, 'fieldValue']}
                          style={{ width: 160 }}
                          labelCol={{ span: 24 }}
                          wrapperCol={{ span: 24 }}>
                          {
                            fieldItem.fieldType === 'Dropdown' &&
                            <Select
                              mode="multiple"
                              placeholder={t('common.pleaseSelect')}
                              options={fieldOption} allowClear />
                          }
                          {
                            fieldItem?.fieldType === 'Text Input' &&
                            <Input />
                          }
                          {
                            fieldItem?.fieldType === 'Number Input' &&
                            <InputNumber style={{ width: '100%' }} addonBefore={selectBefore(index)} />
                          }
                          {
                            fieldItem?.fieldType === 'Date picker' &&
                            <DatePicker style={{ width: '100%' }} placeholder={t('common.pleaseSelect')} format={DATEFORMAT} />
                          }
                        </Form.Item>
                        <Button type="link" className='del-btn' onClick={() => { remove(field.name); }}>
                          <DeleteOutlined />
                        </Button>
                      </Flex>
                    )
                  })}
                </>
              )}
            </Form.List>
            <Button
              className='search-btn'
              type="primary"
              onClick={serach}
              icon={<SearchOutlined style={{ fontSize: 20 }} />}
            />

          </Flex>
        </Form>
        <Form form={formDynamic} className='filter-wrap' name='bigFileDynamicFilterform'>
          <Flex align='center' className='big-file-summary-dynamic-filter-wrap'>
            <Form.Item name="fieldType"
              rules={[
                {
                  required: true,
                  message: t('common.pleaseSelect'),
                },
              ]}
              label='' style={{ width: '200px' }}>
              <Select placeholder={t('common.type')} allowClear options={fieldTypeList} onChange={(val) => fieldTypeChange(val)} />
            </Form.Item>
            <Form.Item name="filedItem"
              rules={[
                {
                  required: true,
                  message: t('common.pleaseSelect'),
                },
              ]}
              label='' style={{ width: '200px' }}>
              <Select placeholder={t('common.item')} allowClear options={filedItems} onChange={(val) => filedItemChange(val)} />
            </Form.Item>
            <Button type="primary" onClick={() => { filedItemAdd() }} style={{ marginTop: '-25px' }}>{t('common.addFilterItem')}</Button>
          </Flex>
        </Form>

        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
          }}
          scroll={{ x: 1500, y: 'calc(100vh)' }}
          columns={tableColumns}
          dataSource={dataList}
          size='small'
          rowKey='bigFileProductId'
          pagination={{
            total: totalPage,
            current: currentPage,
            pageSize: pageSize,
            onChange: (_crrentPage, _pageSize) => {
              setCurrentPage(_crrentPage);
              setPageSize(_pageSize);
              queryList(_crrentPage, _pageSize);
            },
            pageSizeOptions: [10, 20, 50],
            showSizeChanger: true,
            showTotal: (total) => {
              return `Total ${total} items`;
            },
          }}
        />
      </div>

      {
        contentView &&
        <Modal
          title={t('common.fileAnalysisContent')}
          width={1000}
          onCancel={() => setContentView(false)}
          open={contentView}
          footer={[
            <Button key='close' onClick={() => setContentView(false)}>{t('common.close')}</Button>
          ]}>
          {
            recordData?.fileAnalysisContent?.length > 0 ?
              <div style={{ maxHeight: '500px', overflowY: 'auto' }}>
                <div style={{ width: '94%' }}>
                  <FileAnalysisContent analysisContents={recordData?.fileAnalysisContent} />
                </div>
              </div>
              :
              <Flex style={{ fontSize: '16px', width: '90%', color: '#666666', height: '100px', }} justify='center' align='center'>{t('common.noData')}</Flex>
          }

        </Modal>
      }
    </>
  )
};

export default BigSimulationFileSummaryData;
